<template>
  <div class="hotel-reports">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>酒店违规举报管理</span>
          <el-button-group>
            <el-button type="primary" @click="handleBatchProcess"
              >批量处理</el-button
            >
            <el-button type="success" @click="exportReports"
              >导出数据</el-button
            >
          </el-button-group>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="酒店名称">
          <el-input
            v-model="searchForm.hotelName"
            placeholder="请输入酒店名称"
          />
        </el-form-item>
        <el-form-item label="举报类型">
          <el-select
            v-model="searchForm.reportType"
            placeholder="请选择举报类型"
          >
            <el-option label="虚假宣传" value="false_advertising" />
            <el-option label="服务质量" value="service_quality" />
            <el-option label="卫生问题" value="hygiene" />
            <el-option label="价格欺诈" value="price_fraud" />
            <el-option label="其他" value="others" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态">
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已处理" value="processed" />
            <el-option label="已驳回" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="举报时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="sortedReportsList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无举报数据" 
              :image-size="200"
            >
              <div class="empty-text">还没有任何违规举报记录</div>
              <div class="empty-subtext">举报记录将在此处显示</div>
            </el-empty>
          </div>
        </template>
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="reportId"
          label="举报ID"
          width="120"
          sortable="custom"
        />
        <el-table-column
          prop="hotelName"
          label="酒店名称"
          min-width="180"
          sortable="custom"
        />
        <el-table-column prop="hotelType" label="酒店类型" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ getHotelTypeLabel(row.hotelType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="reportType"
          label="举报类型"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag :type="getReportTypeTag(row.reportType)">
              {{ getReportTypeLabel(row.reportType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="reportContent"
          label="举报内容"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="reporterInfo"
          label="举报人"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="reportTime"
          label="举报时间"
          width="160"
          sortable="custom"
        />
        <el-table-column
          prop="status"
          label="处理状态"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                :disabled="row.status === 'processed'"
                @click="handleProcess(row)"
              >
                处理
              </el-button>
              <el-button type="info" size="small" @click="viewDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 处理对话框 -->
    <el-dialog v-model="processDialogVisible" title="处理举报" width="500px">
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理方式" prop="processResult">
          <el-select
            v-model="processForm.processResult"
            placeholder="请选择处理方式"
          >
            <el-option label="警告" value="warning" />
            <el-option label="罚款" value="fine" />
            <el-option label="限制经营" value="restriction" />
            <el-option label="下架房型" value="remove_room" />
            <el-option label="永久封禁" value="permanent_ban" />
            <el-option label="驳回举报" value="reject" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="罚款金额"
          prop="fineAmount"
          v-if="processForm.processResult === 'fine'"
        >
          <el-input-number
            v-model="processForm.fineAmount"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item
          label="限制天数"
          prop="restrictionDays"
          v-if="processForm.processResult === 'restriction'"
        >
          <el-input-number
            v-model="processForm.restrictionDays"
            :min="1"
            :max="365"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="处理说明" prop="description">
          <el-input
            v-model="processForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入处理说明"
          />
        </el-form-item>
        <el-form-item label="处理凭证">
          <el-upload
            action="/api/admin/upload"
            list-type="picture-card"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="通知酒店">
          <el-switch v-model="processForm.notifyHotel" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="举报详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="举报ID">{{
          currentDetail.reportId
        }}</el-descriptions-item>
        <el-descriptions-item label="酒店名称">{{
          currentDetail.hotelName
        }}</el-descriptions-item>
        <el-descriptions-item label="举报类型">
          <el-tag :type="getReportTypeTag(currentDetail.reportType)">
            {{ getReportTypeLabel(currentDetail.reportType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="举报时间">{{
          currentDetail.reportTime
        }}</el-descriptions-item>
        <el-descriptions-item label="举报人">{{
          currentDetail.reporterInfo
        }}</el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getStatusTag(currentDetail.status)">
            {{ getStatusLabel(currentDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="举报内容" :span="2">
          {{ currentDetail.reportContent }}
        </el-descriptions-item>
        <el-descriptions-item label="证据材料" :span="2">
          <el-image
            v-for="(url, index) in currentDetail.evidences"
            :key="index"
            :src="url"
            :preview-src-list="currentDetail.evidences"
            fit="cover"
            class="evidence-image"
          />
        </el-descriptions-item>
        <el-descriptions-item
          v-if="currentDetail.status === 'processed'"
          label="处理结果"
          :span="2"
        >
          <div>
            处理方式：{{ getProcessResultLabel(currentDetail.processResult) }}
          </div>
          <div>处理说明：{{ currentDetail.processDescription }}</div>
          <div>处理时间：{{ currentDetail.processTime }}</div>
          <div>处理人员：{{ currentDetail.processor }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import axios from "@/api/axios";
import * as XLSX from "xlsx";

// 搜索表单
const searchForm = reactive({
  hotelName: "",
  reportType: "",
  status: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const reportsList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedReports = ref([]);
const sortConfig = reactive({
  prop: "",
  order: "",
});

// 处理对话框
const processDialogVisible = ref(false);
const processFormRef = ref(null);
const processForm = reactive({
  processResult: "",
  fineAmount: 0,
  restrictionDays: 1,
  description: "",
  notifyHotel: true,
});

// 表单验证规则
const processRules = {
  processResult: [
    { required: true, message: "请选择处理方式", trigger: "change" },
  ],
  fineAmount: [{ required: true, message: "请输入罚款金额", trigger: "blur" }],
  restrictionDays: [
    { required: true, message: "请输入限制天数", trigger: "blur" },
  ],
  description: [{ required: true, message: "请输入处理说明", trigger: "blur" }],
};

// 详情对话框
const detailDialogVisible = ref(false);
const currentDetail = ref({});

// 测试数据
const mockReports = [
  {
    reportId: "R202403010001",
    hotelName: "桂林大公馆酒店",
    hotelType: "luxury",
    reportType: "false_advertising",
    reportContent: "房间实际面积与网站宣传不符，宣传40平米实际只有30平米",
    reporterInfo: "张先生",
    reportTime: "2024-03-01 10:30:00",
    status: "pending",
    evidences: ["/mock/evidence1.jpg", "/mock/evidence2.jpg"],
    orderId: "O202403010001",
  },
  {
    reportId: "R202403010002",
    hotelName: "桂林温馨家庭旅馆",
    hotelType: "economy",
    reportType: "hygiene",
    reportContent: "房间卫生状况很差，发现蟑螂，床单有污渍未更换",
    reporterInfo: "李女士",
    reportTime: "2024-03-01 14:20:00",
    status: "processing",
    evidences: ["/mock/evidence3.jpg", "/mock/evidence4.jpg"],
    orderId: "O202403010015",
  },
  {
    reportId: "R202403010003",
    hotelName: "桂林商务酒店",
    hotelType: "business",
    reportType: "price_fraud",
    reportContent: "入住时价格与预订时不符，额外收取服务费",
    reporterInfo: "王先生",
    reportTime: "2024-03-01 16:45:00",
    status: "processed",
    evidences: ["/mock/evidence5.jpg"],
    orderId: "O202403010023",
    processResult: "fine",
    processDescription: "经查实存在价格欺诈行为，处以2000元罚款",
    processTime: "2024-03-02 09:30:00",
    processor: "管理员A",
  },
  {
    reportId: "R202403010004",
    hotelName: "桂林度假山庄",
    hotelType: "resort",
    reportType: "service_quality",
    reportContent: "服务态度恶劣，前台人员对客人态度很差",
    reporterInfo: "赵女士",
    reportTime: "2024-03-01 18:15:00",
    status: "rejected",
    evidences: ["/mock/evidence6.jpg"],
    orderId: "O202403010035",
    processResult: "reject",
    processDescription:
      "经调查核实，当时是客人要求提前入住但房间未准备好导致误会",
    processTime: "2024-03-02 10:20:00",
    processor: "管理员B",
  },
];

// 获取酒店类型标签
const getHotelTypeLabel = (type) => {
  const types = {
    economy: "经济型",
    business: "商务型",
    luxury: "豪华型",
    resort: "度假型",
    boutique: "精品型",
  };
  return types[type] || type;
};

// 获取举报类型标签
const getReportTypeLabel = (type) => {
  const types = {
    false_advertising: "虚假宣传",
    service_quality: "服务质量",
    hygiene: "卫生问题",
    price_fraud: "价格欺诈",
    others: "其他",
  };
  return types[type] || type;
};

// 获取举报类型标签样式
const getReportTypeTag = (type) => {
  const tags = {
    false_advertising: "warning",
    service_quality: "info",
    hygiene: "danger",
    price_fraud: "error",
    others: "",
  };
  return tags[type] || "";
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    pending: "待处理",
    processing: "处理中",
    processed: "已处理",
    rejected: "已驳回",
  };
  return statuses[status] || status;
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const tags = {
    pending: "warning",
    processing: "info",
    processed: "success",
    rejected: "danger",
  };
  return tags[status] || "";
};

// 获取处理结果标签
const getProcessResultLabel = (result) => {
  const results = {
    warning: "警告",
    fine: "罚款",
    restriction: "限制经营",
    remove_room: "下架房型",
    permanent_ban: "永久封禁",
    reject: "驳回举报",
  };
  return results[result] || result;
};

// 排序后的列表数据
const sortedReportsList = computed(() => {
  const list = [...reportsList.value];
  if (sortConfig.prop && sortConfig.order) {
    list.sort((a, b) => {
      let compareResult = 0;
      if (typeof a[sortConfig.prop] === "string") {
        compareResult = a[sortConfig.prop].localeCompare(b[sortConfig.prop]);
      } else {
        compareResult = a[sortConfig.prop] - b[sortConfig.prop];
      }
      return sortConfig.order === "ascending" ? compareResult : -compareResult;
    });
  }
  return list;
});

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
};

// 获取举报列表数据
const fetchReportsList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      hotelName: searchForm.hotelName || undefined,
      reportType: searchForm.reportType || undefined,
      status: searchForm.status || undefined,
    };

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0];
      params.endDate = searchForm.dateRange[1];
    }

    const result = await axios.get("/admin/hotels/reports", { params });
    
    if (result.code === 200 && result.data) {
      reportsList.value = result.data.records || [];
      total.value = result.data.total || 0;
    } else {
      // 使用测试数据
      const filtered = filterMockData();
      reportsList.value = filtered;
      total.value = filtered.length;
    }
  } catch (error) {
    console.error("获取举报列表失败：", error);
    ElMessage.error("获取举报列表失败，使用测试数据");
    
    // 使用测试数据
    const filtered = filterMockData();
    reportsList.value = filtered;
    total.value = filtered.length;
  } finally {
    loading.value = false;
  }
};

// 根据搜索条件过滤测试数据
const filterMockData = () => {
  let filteredList = [...mockReports];

  if (searchForm.hotelName) {
    filteredList = filteredList.filter((item) =>
      item.hotelName.toLowerCase().includes(searchForm.hotelName.toLowerCase()),
    );
  }

  if (searchForm.reportType) {
    filteredList = filteredList.filter(
      (item) => item.reportType === searchForm.reportType,
    );
  }

  if (searchForm.status) {
    filteredList = filteredList.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const startDate = new Date(searchForm.dateRange[0]).getTime();
    const endDate = new Date(searchForm.dateRange[1]).getTime();
    filteredList = filteredList.filter((item) => {
      const reportTime = new Date(item.reportTime).getTime();
      return reportTime >= startDate && reportTime <= endDate;
    });
  }

  return filteredList;
};

// 初始化数据
onMounted(() => {
  fetchReportsList();
});

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchReportsList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedReports.value = val;
};

// 处理单个举报
const handleProcess = (row) => {
  processForm.processResult = "";
  processForm.fineAmount = 0;
  processForm.restrictionDays = 1;
  processForm.description = "";
  processForm.notifyHotel = true;

  currentDetail.value = row;
  processDialogVisible.value = true;
};

// 查看详情
const viewDetail = (row) => {
  currentDetail.value = row;
  detailDialogVisible.value = true;
};

// 提交处理
const submitProcess = async () => {
  if (!processFormRef.value) return;
  
  try {
    const valid = await processFormRef.value.validate();
    if (valid) {
      const processData = {
        reportId: currentDetail.value.reportId,
        processResult: processForm.processResult,
        description: processForm.description,
        notifyHotel: processForm.notifyHotel
      };

      // 添加特定处理类型的额外数据
      if (processForm.processResult === "fine") {
        processData.fineAmount = processForm.fineAmount;
      }
      if (processForm.processResult === "restriction") {
        processData.restrictionDays = processForm.restrictionDays;
      }

      try {
        const res = await axios.post("/admin/hotels/reports/process", processData);
        
        if (res.code === 200) {
          ElMessage.success("处理成功");
          processDialogVisible.value = false;
          fetchReportsList();
        } else {
          // 如果后端API调用失败，使用测试数据进行模拟
          simulateProcess();
        }
      } catch (error) {
        console.error("提交处理失败：", error);
        ElMessage.error("提交处理失败，使用模拟数据");
        
        // 模拟处理成功
        simulateProcess();
      }
    }
  } catch (error) {
    console.error("表单验证失败：", error);
  }
};

// 模拟处理举报
const simulateProcess = () => {
  const currentReport = reportsList.value.find(
    (item) => item.reportId === currentDetail.value.reportId,
  );
  
  if (currentReport) {
    currentReport.status = "processed";
    currentReport.processResult = processForm.processResult;
    currentReport.processDescription = processForm.description;
    currentReport.processTime = new Date().toLocaleString();
    currentReport.processor = "当前管理员";

    if (processForm.processResult === "fine") {
      currentReport.fineAmount = processForm.fineAmount;
    }
    if (processForm.processResult === "restriction") {
      currentReport.restrictionDays = processForm.restrictionDays;
    }

    ElMessage.success("处理成功（使用模拟数据）");
    processDialogVisible.value = false;
  }
};

// 导出数据
const exportReports = () => {
  // 创建一个工作簿
  const wb = XLSX.utils.book_new();
  
  // 准备导出数据
  const exportData = reportsList.value.map(item => ({
    '举报ID': item.reportId,
    '酒店名称': item.hotelName,
    '酒店类型': getHotelTypeLabel(item.hotelType),
    '举报类型': getReportTypeLabel(item.reportType),
    '举报内容': item.reportContent,
    '举报人': item.reporterInfo,
    '举报时间': item.reportTime,
    '处理状态': getStatusLabel(item.status),
    '处理结果': item.processResult ? getProcessResultLabel(item.processResult) : '',
    '处理说明': item.processDescription || '',
    '处理时间': item.processTime || '',
    '处理人员': item.processor || ''
  }));
  
  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(exportData);
  
  // 设置列宽
  const colWidths = [
    { wch: 15 }, // 举报ID
    { wch: 20 }, // 酒店名称
    { wch: 10 }, // 酒店类型
    { wch: 12 }, // 举报类型
    { wch: 40 }, // 举报内容
    { wch: 10 }, // 举报人
    { wch: 20 }, // 举报时间
    { wch: 10 }, // 处理状态
    { wch: 15 }, // 处理结果
    { wch: 40 }, // 处理说明
    { wch: 20 }, // 处理时间
    { wch: 15 }  // 处理人员
  ];
  
  ws['!cols'] = colWidths;
  
  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '酒店违规举报数据');
  
  // 生成Excel文件并下载
  const timestamp = new Date().getTime();
  const filename = `酒店违规举报数据_${timestamp}.xlsx`;
  XLSX.writeFile(wb, filename);
  
  ElMessage.success(`已导出文件：${filename}`);
};

// 批量处理
const handleBatchProcess = async () => {
  if (selectedReports.value.length === 0) {
    ElMessage.warning("请选择要处理的举报");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量处理选中的 ${selectedReports.value.length} 条举报吗？`,
      "批量处理",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    
    const ids = selectedReports.value.map(report => report.reportId);
    
    try {
      const res = await axios.post("/admin/hotels/reports/batch-process", { ids });
      
      if (res.code === 200) {
        ElMessage.success("批量处理已开始");
        fetchReportsList();
      } else {
        // 模拟批量处理
        simulateBatchProcess();
      }
    } catch (error) {
      console.error("批量处理失败：", error);
      ElMessage.error("批量处理失败，使用模拟数据");
      
      // 模拟批量处理
      simulateBatchProcess();
    }
  } catch (error) {
    // 用户取消操作
    ElMessage.info("已取消批量处理");
  }
};

// 模拟批量处理
const simulateBatchProcess = () => {
  selectedReports.value.forEach((report) => {
    const item = reportsList.value.find(
      (item) => item.reportId === report.reportId,
    );
    if (item && item.status === "pending") {
      item.status = "processing";
    }
  });
  ElMessage.success("批量处理已开始（使用模拟数据）");
};

// 文件上传相关方法
const handlePreview = (file) => {
  window.open(file.url);
};

const handleRemove = (file, fileList) => {
  ElMessageBox.confirm("确定要删除这个文件吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchReportsList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchReportsList();
};
</script>

<style scoped>
.hotel-reports {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.evidence-image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.empty-state {
  padding: 40px 0;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
